package com.starrocks.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;

/**
 * 数据源配置类
 * 配置StarRocks和TiDB两个数据源
 * MyBatis Plus 使用 TiDB 数据源（存储配置信息）
 */
@Configuration
@MapperScan(basePackages = "com.starrocks.mapper", sqlSessionFactoryRef = "sqlSessionFactory")
public class DataSourceConfig {

    /**
     * StarRocks数据源（源数据库）
     */
    @Bean(name = "starrocksDataSource")
    @ConfigurationProperties(prefix = "starrocks.datasource")
    public DataSource starrocksDataSource() {
        return DataSourceBuilder.create()
                .type(HikariDataSource.class)
                .build();
    }

    /**
     * TiDB数据源（目标数据库 + MyBatis Plus主数据源）
     */
    @Primary
    @Bean(name = "tidbDataSource")
    @ConfigurationProperties(prefix = "tidb.datasource")
    public DataSource tidbDataSource() {
        return DataSourceBuilder.create()
                .type(HikariDataSource.class)
                .build();
    }

    /**
     * StarRocks的JdbcTemplate
     */
    @Primary
    @Bean(name = "starrocksJdbcTemplate")
    public JdbcTemplate starrocksJdbcTemplate(@Qualifier("starrocksDataSource") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

    /**
     * TiDB的JdbcTemplate
     */
    @Bean(name = "tidbJdbcTemplate")
    public JdbcTemplate tidbJdbcTemplate(@Qualifier("tidbDataSource") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }
    
    /**
     * MyBatis Plus SqlSessionFactory（使用TiDB数据源）
     */
    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("tidbDataSource") DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean factoryBean = new MybatisSqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        
        // 添加分页插件
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        factoryBean.setPlugins(interceptor);
        
        return factoryBean.getObject();
    }
}